/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dataanalysis.gui.filechooser;

import java.awt.Component;
import java.awt.HeadlessException;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import weka.gui.ExtensionFileFilter;

/**
 *
 * @author Administrator
 */
public class MyFileChooser extends JFileChooser {

    public MyFileChooser(File curFile) {
        super(curFile);
        this.setMultiSelectionEnabled(false);
        this.setAcceptAllFileFilterUsed(false);
        this.setFileSelectionMode(JFileChooser.FILES_ONLY);
    }

    @Override
    public void approveSelection() {
        File savedFile = new File(getSavePath());

        if (savedFile.exists()) {
            int overwriteSelect = JOptionPane.showConfirmDialog(this,
                    "<html><font size=3>文件" + savedFile.getName() + "已存在，是否覆盖?</font><html>",
                    "是否覆盖?",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
            if (overwriteSelect != JOptionPane.YES_OPTION) {
                return;
            }
        }
        super.approveSelection();
    }

    public String getSavePath() {
        String path = this.getSelectedFile().getAbsolutePath();
        int index = path.lastIndexOf(".");
        if (index != -1) {
            path = path.substring(0, index);
        }
        path += getExtension();
        return path;
    }

    private String getExtension() {
        return ((ExtensionFileFilter) this.getFileFilter()).getExtensions()[0];
    }

    @Override
    public int showSaveDialog(Component parent) throws HeadlessException {
        this.setSelectedFile(new File(this.getCurrentDirectory().getAbsolutePath() + "\\未命名" + getExtension()));
        return super.showSaveDialog(parent);
    }
}
